package com.yang.common.context;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Map;
import java.util.Optional;

/**
 * @author: Billyang
 * @date: 2024/10/01 23:30
 */
@Slf4j
@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static <T> T getBean(String name) {
        if (context == null) {
            return null;
        }
        return (T) context.getBean(name);
    }

    public static <T> T getBean(Class<T> requiredType) {
        if (context == null) {
            return null;
        }
        return context.getBean(requiredType);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        if (context == null) {
            return null;
        }
        try {
            return context.getBean(name, requiredType);
        } catch (BeansException e) {
            log.error("has not been", e);
        }
        return null;
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> requiredType) {
        if (context == null) {
            return Collections.emptyMap();
        }
        return context.getBeansOfType(requiredType);
    }

    public static String getProperty(String key, String defaultValue) {
        if (context == null) {
            return defaultValue;
        }
        return context.getEnvironment().getProperty(key, defaultValue);
    }

    public static String getProperty(String key) {
        if (context == null) {
            return null;
        }
        return context.getEnvironment().getProperty(key);
    }

    public static int getIntegerProperty(String key, int defaultValue) {
        return Optional.ofNullable(getProperty(key)).map(Integer::parseInt).orElse(defaultValue);
    }

    public static boolean getBooleanProperty(String key, boolean defaultValue) {
        return Optional.ofNullable(getProperty(key)).map(Boolean::parseBoolean).orElse(defaultValue);
    }

}
